package com.example.audiostreaming.data;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.audiostreaming.Bean.UserBean;
import com.example.audiostreaming.Bean.UserDataBean;
import com.example.audiostreaming.utils.UtilConstants;
import com.example.audiostreaming.utils.UtilLog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.album.Announcer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.example.audiostreaming.base.BaseApplication.getAppContext;

public class SubscriptionDao implements ISubDao {
    private static final String TAG = "SubscriptionDao";

    private final XimalayaDBHelper mDBHelper;
    private Object mLock = new Object();
    private ISubDaoCallback mCallback=null;


    public SubscriptionDao() {
        mDBHelper = new XimalayaDBHelper(getAppContext());
    }

    @Override
    public void setCallback(ISubDaoCallback callback) {
        this.mCallback = callback;
    }

    @Override
    public void addAlbum(Album album, boolean isSynchronize) {
        synchronized(mLock){
            SQLiteDatabase db=null;
            boolean isSuccess = false;
            try {
                db = mDBHelper.getWritableDatabase();
                db.beginTransaction();//开启事务

                ContentValues values = new ContentValues();
                values.put(UtilConstants.SUB_ALBUM_ID, album.getId());
                values.put(UtilConstants.SUB_TITLE, album.getAlbumTitle());
                values.put(UtilConstants.SUB_COVER_URL, album.getCoverUrlLarge());
                values.put(UtilConstants.SUB_DESCRIPTION, album.getAlbumIntro());
                values.put(UtilConstants.SUB_TRACKS_COUNT, album.getIncludeTrackCount());
                values.put(UtilConstants.SUB_PLAY_COUNT, album.getPlayCount());
                values.put(UtilConstants.SUB_AUTHOR_NAME, album.getAnnouncer().getNickname());

                if (isSynchronize) {
//                UserDataBean userDataBean = UserDataBean.getUserDataBean();
                    UserDataBean userDataBean = new UserDataBean();
                    userDataBean.setTelephone(UserBean.getUserBean().getTelephone());
                    userDataBean.setName(UserBean.getUserBean().getName());
                    userDataBean.setId(album.getId());
                    userDataBean.setAlbumTitle(album.getAlbumTitle());
                    userDataBean.setCoverUrlLarge(album.getCoverUrlLarge());
                    userDataBean.setAlbumIntro(album.getAlbumIntro());
                    userDataBean.setIncludeTrackCount(album.getIncludeTrackCount());
                    userDataBean.setPlayCount(album.getPlayCount());
                    userDataBean.setNickname(album.getAnnouncer().getNickname());

                    uploadAddUserDataBean(userDataBean);//上传服务器
                }

                db.insert(UtilConstants.SUB_TB_NAME, null, values);
                db.setTransactionSuccessful();
                isSuccess = true;
            }catch (Exception e){
                isSuccess = false;
                e.printStackTrace();
            }finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }
                if (mCallback != null) {
                    mCallback.onAddResult(isSuccess);
                }
            }

        }
    }

    private void uploadAddUserDataBean(UserDataBean userDataBean) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        String s = gson.toJson(userDataBean);

        String mUrl = "http://192.168.0.107:8080/AndioStreamingService_war_exploded/";
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=GBK"), s);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mUrl + "addUserDataBean").post(requestBody).build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure ==> "+e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.d(TAG, "onResponse: "+string);
            }
        });
    }

    @Override
    public void delAlbum(Album album) {
        synchronized (mLock) {
            SQLiteDatabase db = null;
            boolean isDeleteSuccess = false;
            try {
                db = mDBHelper.getWritableDatabase();
                db.beginTransaction();

//                UserDataBean userDataBean = UserDataBean.getUserDataBean();
                UserDataBean userDataBean = new UserDataBean();
                userDataBean.setTelephone(UserBean.getUserBean().getTelephone());
                userDataBean.setId(album.getId());

                uploadDelUserDataBean(userDataBean);

                int delete = db.delete(UtilConstants.SUB_TB_NAME, UtilConstants.SUB_ALBUM_ID + "=?", new String[]{album.getId() + ""});
                UtilLog.d(TAG, "delete -- > " + delete);
                db.setTransactionSuccessful();
                isDeleteSuccess = true;
            }catch (Exception e){
                e.printStackTrace();
                isDeleteSuccess = false;
            }finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }
                if (mCallback != null) {
                    mCallback.onDelResult(isDeleteSuccess);
                }
            }
        }
    }

    private void uploadDelUserDataBean(UserDataBean userDataBean) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();
        Gson gson = gsonBuilder.create();
        String s = gson.toJson(userDataBean);

        String mUrl = "http://192.168.0.107:8080/AndioStreamingService_war_exploded/";
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain;charset=GBK"), s);
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(mUrl + "delUserDataBean").post(requestBody).build();

        Call call = okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure ==> "+e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.d(TAG, "onResponse: "+string);
            }
        });
    }

    @Override
    public void listAlbums() {
        synchronized (mLock) {
            SQLiteDatabase db = null;
            List<Album> subAlbums = new ArrayList<>();
            try {
                db = mDBHelper.getReadableDatabase();
                db.beginTransaction();
                Cursor cursor = db.query(UtilConstants.SUB_TB_NAME, null, null, null, null, null, "_id desc");
                while (cursor.moveToNext()) {
                    Album album = new Album();

                    String coverUrl = cursor.getString(cursor.getColumnIndex(UtilConstants.SUB_COVER_URL));
                    album.setCoverUrlLarge(coverUrl);
                    //
                    String title = cursor.getString(cursor.getColumnIndex(UtilConstants.SUB_TITLE));
                    album.setAlbumTitle(title);
                    //
                    String description = cursor.getString(cursor.getColumnIndex(UtilConstants.SUB_DESCRIPTION));
                    album.setAlbumIntro(description);
                    //
                    int tracksCount = cursor.getInt(cursor.getColumnIndex(UtilConstants.SUB_TRACKS_COUNT));
                    album.setIncludeTrackCount(tracksCount);
                    //
                    int playCount = cursor.getInt(cursor.getColumnIndex(UtilConstants.SUB_PLAY_COUNT));
                    album.setPlayCount(playCount);
                    //
                    int albumId = cursor.getInt(cursor.getColumnIndex(UtilConstants.SUB_ALBUM_ID));
                    album.setId(albumId);
                    String authorName = cursor.getString(cursor.getColumnIndex(UtilConstants.SUB_AUTHOR_NAME));
                    Announcer announcer = new Announcer();
                    announcer.setNickname(authorName);
                    album.setAnnouncer(announcer);
                    subAlbums.add(album);
                }
                db.setTransactionSuccessful();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }
                if (mCallback != null) {
                    mCallback.onSubListLoaded(subAlbums);
                }
            }
        }
    }

    @Override
    public void clearAlbum() {
        synchronized (mLock) {
            SQLiteDatabase db = null;
            boolean isDeleteSuccess = false;
            try {
                db = mDBHelper.getWritableDatabase();
                db.beginTransaction();
                db.delete(UtilConstants.SUB_TB_NAME, null, null);
                db.setTransactionSuccessful();
                isDeleteSuccess = true;
            } catch (Exception e) {
                e.printStackTrace();
                isDeleteSuccess = false;
            } finally {
                if (db != null) {
                    db.endTransaction();
                    db.close();
                }
                if (mCallback != null) {
                    mCallback.onSubClean(isDeleteSuccess);
                }
            }
        }
    }
}
